﻿using UnityEngine;
using System.Collections.Generic;
using ProtoBuf.Message;
using Dict;
using Dict.DataModel;
using Dict.Config;
using System;

namespace UI
{

    public class UIDropData
    {
        public Dictionary<string, int> drop_dict = new Dictionary<string, int>();

        public UIDropData( string drop_str )
        {
            var drop_infos = drop_str.Trim().Split( new char[1] { ';' }, System.StringSplitOptions.RemoveEmptyEntries );
            foreach( var drop_s in drop_infos )
            {
                if( drop_s.Contains( "," ) )
                {
                    var drop_message = drop_s.Trim().Split( new char[1] { ',' }, System.StringSplitOptions.RemoveEmptyEntries );
                    var drop_id = drop_message[0];
                    var drop_number = int.Parse( drop_message[1] );
                    if( drop_dict.ContainsKey( drop_id ) )
                    {
                        drop_dict[drop_id]+= drop_number;
                    }
                    else
                    {
                        drop_dict[drop_id]=drop_number;
                    }
                }
                else
                {
                    drop_dict[drop_s]=0;
                }
            }
        }

        public List<BaseResource> toBaseResource()
        {
            List<BaseResource> ls = new List<BaseResource>();

            foreach (var kvp in drop_dict)
            {
                var bb = new BaseResource();
                bb.id = kvp.Key;
                bb.num = kvp.Value;
                bb.guid = "";
                ls.Add(bb);
            }

            return ls;
        }

    }
   
    public class UICopyData
    {
        public List<UIChapterData> copy_chapters = new List<UIChapterData>();
        public static Dictionary<string, UIChapterData> chapter_dict = new Dictionary<string, UIChapterData>();
        public static Dictionary<string, UILevelData> level_dict = new Dictionary<string, UILevelData>();

        public bool has_init=false;

        public UICopyData()
        {
            this.has_init = false;

            var chapters = Dict.Blo.DictCopyChapterBlo.GetAllChapters();
            foreach( var chapter in chapters )
            {
                copy_chapters.Add( new UIChapterData( chapter ) );
            }

            copy_chapters.Sort( ( lh, rh ) =>
            {
                if( lh.chapter_seq > rh.chapter_seq ) return 1; return -1;
            } );
        }

        public void SetPassedCopyInfo( SCCopyPassedInfo info )
        {
            this.has_init=true;

            foreach( var it in info.passedCopyInfo )
            {
                var chapterId = it.chapterId+"";
                var levelId = it.missionId+"";
                int star = it.star;
                int challenge = it.challengeTimes;

                SetLevelStar( chapterId, levelId, star );
                SetLevelChallenge( chapterId, levelId, challenge );
                SetCopyOpenInfo( chapterId, levelId, it.isOpen );
            }

            foreach(var it in info.passedChapterInfo)
            {
                var chapterId = it.chapterId;
                var box0 = it.reward0Claimed;
                var box1 = it.reward1Claimed;
                var box2 = it.reward2Claimed;
     
                SetChapterBox( chapterId, box0, box1, box2 );
            }

            SetCurrentOpenInfo(info.currentChapterId, info.currentMissionId);

            if ( string.IsNullOrEmpty( StaticData.currFightLevelId ) )
            {
                StaticData.currFightLevelId = info.currentMissionId;
            }
            if( string.IsNullOrEmpty( StaticData.currFightChapterId ) )
            {
                StaticData.currFightChapterId = info.currentChapterId;
            }
        }

        public void Clear()
        {
            copy_chapters.Clear();
        }

        public void SetLevelStar( string chapterId, string levelId, int star )
        {
            var level = GetUILevelData( chapterId, levelId );
            level.level_inst_star = star;
        }

        public void SetLevelChallenge(string chapterId,string levelId,int challenge)
        {
            var level = GetUILevelData( chapterId, levelId );
            level.level_curr_challenge = challenge;

#if UNITY_EDITOR
//            Debug.Log("[DEBUG] level has challenge count:" + level.level_curr_challenge);
#endif
        }

        public void SetCurrentOpenInfo(string chapterId,string levelId)
        {
            GetUIChapterData(chapterId).chapter_inst_open = true;
            GetUILevelData(chapterId, levelId).level_inst_open = true;
        }

        public void SetCopyOpenInfo(string chapterId,string levelId,int isOpen)
        {
            bool opend = isOpen==1;
            var chapter = GetUIChapterData(chapterId);
            chapter.chapter_inst_open = opend;
            var level = GetUILevelData( chapter, levelId );
            level.level_inst_open = opend;
        }

        public void SetChapterBox(string chapterId,bool box0,bool box1,bool box2)
        {
            var chapter = GetUIChapterData( chapterId );
            chapter.chapter_inst_get_box_0 = box0;
            chapter.chapter_inst_get_box_1 = box1;
            chapter.chapter_inst_get_box_2 = box2;
        }

        #region Setter
        static public void SetUILevelData( string chapterId, UILevelData data )
        {
            var levelData = GetUILevelData( chapterId, data.level_id );
            levelData.Copy( data );
        }

        static public void SetUITaskData( string chapterId, string levelId, UITaskData data )
        {
            var taskData = GetUITaskData( chapterId, levelId, data.task_id );
            taskData.Copy( data );
        }
        #endregion

        #region Getter
        static public UIChapterData GetUIChapterData( string chapterId )
        {
            foreach( var chapter in StaticData.copyData.copy_chapters )
            {
                if( chapterId == chapter.chapter_id )
                {
                    return chapter;
                }
            }

            return null;
        }

        static public UILevelData GetUILevelData(string levelId )
        {
            foreach (var chapter in StaticData.copyData.copy_chapters)
            {
                foreach (var level in chapter.chapter_levels)
                {
                    if (levelId == level.level_id)
                    {
                        return level;
                    }
                }
            }

            throw new Exception("can't find the level !!");
        }

        static public UILevelData GetUILevelData( UIChapterData chapter, string levelId )
        {
            foreach( var level in chapter.chapter_levels )
            {
                if( levelId== level.level_id )
                {
                    return level;
                }
            }

            return null;
        }

        static public UILevelData GetUILevelData( string chapterId, string levelId )
        {
            return GetUILevelData( GetUIChapterData( chapterId ), levelId );
        }

        static public UILevelData GetUILevelData( string chapterId, int seq )
        {
            var chapter = GetUIChapterData( chapterId );

            foreach( var level in chapter.chapter_levels )
            {
                if( seq== level.level_seq )
                {
                    return level;
                }
            }

            return null;
        }

        static public UITaskData GetUITaskData( string chapterId, string levelId, string taskId )
        {
            var level = GetUILevelData( GetUIChapterData( chapterId ), levelId );
            foreach( var task in level.level_tasks )
            {
                if( task.task_id == taskId ) return task;
            }

            return null;
        }

        static public UIChapterData GetNextChapterData( string chapterId )
        {
            int current_seq = 1;
            foreach (var chapterData in StaticData.copyData.copy_chapters)
            {
                if( chapterId == chapterData.chapter_id )
                {
                    break;
                }

                current_seq++;
            }

            if(current_seq+1 <= StaticData.copyData.copy_chapters.Count)
            {
                foreach ( var chapter in StaticData.copyData.copy_chapters)
                {
                    if( chapter.chapter_seq == current_seq+1 ) return chapter;
                }

                return null;
            }
            else
            {
                return null;
            }
        }

        static public UILevelData GetNextLevelData( string chapterId, string levelId )
        {
            var chapterData = GetUIChapterData( chapterId );
            var levelData = GetUILevelData( chapterId, levelId );

            int seq =1;
            if(levelData.level_id == levelId)
            {
                seq = levelData.level_seq;
            }

            if(seq + 1 <= chapterData.chapter_levels.Count)
            {
                foreach (var lv in chapterData.chapter_levels)
                {
                    if( seq+1 == lv.level_seq ) return lv;
                }

                return null;
            }
            else
            {
                return null;
            }
        }

        static public UITaskData GetUITaskData( string chapterId,string levelId,int taskSeq)
        {
            var level = GetUILevelData( GetUIChapterData( chapterId ), levelId );
            foreach( var task in level.level_tasks )
            {
                if( task.task_seq == taskSeq ) return task;
            }

            return null;
        }

        static public int GetChapterStar( string chapterId )
        {
            int star = 0;
            foreach( var level in GetUIChapterData( chapterId ).chapter_levels )
            {
                star+= level.level_inst_star;
            }

            return star;
        }

        /// <summary>
        /// 获取指定章节星星数
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static public int GetChapterStar( UIChapterData data )
        {
            int star = 0;
            foreach( var level in data.chapter_levels )
            {
                star+= level.level_inst_star;
            }

            return star;
        }
        /// <summary>
        /// 获取关卡总星星数
        /// </summary>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        static public int GetChapterAllStar( string chapterId )
        {
            int star=0;
            foreach( var level in GetUIChapterData( chapterId ).chapter_levels )
            {
                star+= level.level_dict_star;
            }

            return star;
        }
        
        /// <summary>
        /// 获取下一关
        /// </summary>
        /// <param name="chapterId"></param>
        /// <param name="levelId"></param>
        static public void GetNextRunningChapterAndLevel(out string chapterId,out string levelId)
        {
            var cur_selection_chapter_id = StaticData.currFightChapterId;
            var cur_selection_level_id= StaticData.currFightLevelId;
            
            /*var levelData = */GetUILevelData( cur_selection_chapter_id, cur_selection_level_id );
            var nextLevelData = GetNextLevelData( cur_selection_chapter_id, cur_selection_level_id );
            
            if(nextLevelData!=null)
            {
                chapterId = cur_selection_chapter_id;
                levelId = nextLevelData.level_id;
            }
            else
            {
                var nextChapterData = GetNextChapterData( cur_selection_chapter_id );
                if(nextChapterData!=null)
                {
                    chapterId = nextChapterData.chapter_id;
                    levelId = GetUILevelData( chapterId, 1 ).level_id;
                }
                else
                {
                    chapterId = cur_selection_level_id;
                    var cdata = GetUIChapterData( chapterId );
                    levelId = cdata.chapter_levels[cdata.chapter_levels.Count-1].level_id;
                }
            }
        }

        /// <summary>
        /// 当前关卡开启
        /// </summary>
        /// <param name="chapterId"></param>
        /// <param name="levelId"></param>
        /// <returns></returns>
        static public bool CurrentLevelOpened(string chapterId,string levelId)
        {
            bool ret=false;
            var currChaper = GetUIChapterData( chapterId );
            var currLevel = GetUILevelData( currChaper, levelId );

            ret = currChaper.chapter_inst_open && currLevel.level_inst_open;

            return ret;
        }

        /// <summary>
        /// 当前关开是不是最后一张
        /// </summary>
        /// <param name="chapterId"></param>
        /// <param name="levelId"></param>
        /// <returns></returns>
        static public bool CurrentLevelIsLastOfChapter(string chapterId,string levelId)
        {
            var chapters = StaticData.copyData.copy_chapters;
            foreach(var chapter in chapters)
            {
                if(chapter.chapter_id == chapterId)
                {
                    var levels = chapter.chapter_levels;
                    var lastLevel = levels[levels.Count - 1];
                    if (lastLevel.level_id == levelId) return true;
                }
            }

            return false;
        }

        /// <summary>
        /// 当前关卡开启
        /// </summary>
        /// <param name="levelId"></param>
        /// <returns></returns>
        static public bool CurrentLevelOpened(string levelId)
        {
            foreach(var chapter in StaticData.copyData.copy_chapters)
            {
                foreach(var level in chapter.chapter_levels)
                {
                    if(levelId == level.level_id)
                    {
                        return level.level_inst_open;
                    }
                }
            }

            throw new Exception("can't find the level !!");
        }

        /// <summary>
        /// 当前关卡是否开启
        /// </summary>
        /// <param name="chapterId"></param>
        /// <returns></returns>
        static public bool CurrentChapterOpened(string chapterId)
        {
            return GetUIChapterData( chapterId ).chapter_inst_open;
        }
        /// <summary>
        /// 增加挑战次数
        /// </summary>
        /// <param name="levelId"></param>
        /// <param name="count"></param>
        static public void AddCurrentLevelChallengeCount(string levelId,int count=1)
        {
            var level = GetUILevelData(levelId);
            level.level_curr_challenge+=count;
            if(level.level_curr_challenge > level.level_max_challenge)
            {
                level.level_curr_challenge = level.level_max_challenge;
            }
            if(level.level_curr_challenge < 0)
            {
                level.level_curr_challenge = 0;
            }
        }
        /// <summary>
        /// 重置挑战次数
        /// </summary>
        /// <param name="levelId"></param>
        static public void ResetCurrentLevelChallengeCount(string levelId)
        {
            var level = GetUILevelData(levelId);
            level.level_curr_challenge = 0;
        }
        /// <summary>
        /// 功能开放
        /// </summary>
        /// <param name="chapterId"></param>
        /// <param name="levelId"></param>
        static public void OpenLevelAndChapterFunction(string chapterId,string levelId)
        {
            var chapter = UICopyData.GetUIChapterData(chapterId + "");
            chapter.chapter_inst_open = true;
            var level = UICopyData.GetUILevelData(levelId + "");
            level.level_inst_open = true;
        }


        /// <summary>
        /// 设置星星的
        /// </summary>
        /// <param name="levelId"></param>
        /// <param name="starCount"></param>
        static public void TryToSetLevelStar(string levelId,int starCount)
        {
            var level = UICopyData.GetUILevelData(levelId);
            if(level.level_inst_star < starCount)
            {
                level.level_inst_star = starCount;
            }
        }

        /// <summary>
        /// 是否为新的关卡
        /// </summary>
        /// <param name="levelId"></param>
        static public bool IsNew(string levelId)
        {
            var level = UICopyData.GetUILevelData(levelId);
            if (level.level_inst_star <= 0) return true;
            return false;
        }
        #endregion
    }
}